﻿namespace Pub.Class
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.CompilerServices;
    using System.Text;

    public static class IDictionaryExtensions
    {
        public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)
        {
            return dictionary.GetValue<TKey, TValue>(key, default(TValue));
        }

        public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue defValue)
        {
            TValue local;
            if (dictionary.TryGetValue(key, out local))
            {
                return local;
            }
            return defValue;
        }

        public static TValue GetValueOrAdd<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key) where TValue: new()
        {
            return dictionary.GetValueOrAdd<TKey, TValue>(key, default(TValue));
        }

        public static TValue GetValueOrAdd<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue defValue) where TValue: new()
        {
            TValue local;
            if (!dictionary.TryGetValue(key, out local))
            {
                local = defValue;
                dictionary.Add(key, defValue);
            }
            return local;
        }

        public static bool IsNullEmpty(this IDictionary self)
        {
            if (!self.IsNull())
            {
                return (self.Count == 0);
            }
            return true;
        }

        public static string ToUrl(this IDictionary parameters)
        {
            if (parameters.IsNull() || (parameters.Count == 0))
            {
                return string.Empty;
            }
            StringBuilder sb = new StringBuilder();
            foreach (string str in parameters.Keys)
            {
                sb.AppendFormat("{0}={1}&", str.UrlEncode(), parameters[str].ToString().UrlEncode());
            }
            sb.RemoveLastChar("&");
            return sb.ToString();
        }
    }
}

